using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;

using NougakudoCompanion.Utils;

namespace AdminWeb
{
    public class WebRole : RoleEntryPoint
    {
        public override bool OnStart()
        {
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            //InstancesManagement.Initialize();   // initialize tabel and queue.    // Move to Run.

            bool ret = false;
            // Create NougakuDo Companion logging folder.
            ret = ShortcutPathUtility.CreateShortcutRoot();
            if (!ret)
            {
                Logging.Write("Failed :: NougakuDo Companion logging folder.");
                return base.OnStart();
            }
            Logging.Write("Role Start");
            try
            {
                // Start NougakuDoController settings and run.
                ret = Nougakudo.Start();
#if DEBUG
                Logging.Write("NougakuDoContoller result =" + ret.ToString());
#endif
            }
            catch (Exception e)
            {
                Logging.Write("Error:" + e.Message);
            }
            Logging.Write("Base OnStart");

            return base.OnStart();
        }

        public override void Run()
        {
#if DEBUG
            Logging.Write("Role Run");
#endif
            InstancesManagement.Initialize();   // initialize tabel and queue.  // Move from OnStart to Run.
            base.Run();
        }

        public override void OnStop()
        {
            Logging.Write("Role Stop");
            try
            {
                InstancesManagement.Terminate();    // cleanup tabel and queue.
#if DEBUG
                Logging.Write("Nougakudo stop");
#endif
                var ret = Nougakudo.Stop();
#if DEBUG
                Logging.Write("NougakuDoController stop wait 30s");
#endif
                System.Threading.Thread.Sleep(30000);
                Logging.Write("NougakuDoController stop result = " + ret.ToString());
            }
            catch (Exception e)
            {
                Logging.Write("NougakuDoController stop error = " + e.Message);
            }
            base.OnStop();
        }

    }
}
